#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Zhangcl
import sys, os, time,shutil
import paramiko
from django.conf import settings
# from threadpool import ThreadPool,makeRequests
from concurrent.futures import ThreadPoolExecutor


def send_file(task_log_obj, local_file, host_file):
    host = task_log_obj.bind_host.host
    print(host)
    user_obj = task_log_obj.bind_host.host_user
    print(user_obj)
    print(host.ip_addr, host.post,user_obj.username,user_obj.password)
    print(local_file,host_file)
    try:
        transport = paramiko.Transport(host.ip_addr, host.post)  # 绑定ip和端口
        transport.connect(username=user_obj.username, password=user_obj.password)  # 进行连接
        sftp = paramiko.SFTPClient.from_transport(transport)
        sftp.put(local_file, host_file)
        print("success")
        task_log_obj.result = "success"
        task_log_obj.status = 0
        task_log_obj.save()
        transport.close()
    except Exception as e:
        task_log_obj.result = e
        task_log_obj.status = 1
        task_log_obj.save()
        print("falus")


if __name__ == '__main__':
    base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    sys.path.append(base_dir)
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CrazyEye.settings")
    import django

    django.setup()

    from web import models

    if len(sys.argv) == 1:
        exit("error:must provide task_id")
    task_id = sys.argv[1]
    local_file = sys.argv[2]
    host_file = sys.argv[3]
    username = sys.argv[4]
    task_obj = models.Task.objects.get(id=task_id)
    print(task_obj)

    # 1. 生成多线程
    pool = ThreadPoolExecutor(10)
    for task_log_detail_obj in task_obj.tasklogdetail_set.all():
        print(task_log_detail_obj)
        pool.submit(send_file, task_log_detail_obj, local_file, host_file)

    pool.shutdown(wait=True)
    os.remove(local_file)
    upload_dir = os.path.join(settings.FILE_UPLOAD_DIR, username)
    shutil.rmtree(upload_dir)
